package com.university.trade.servlet;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.university.trade.util.PropertiesUtil;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
 * 图片验证码 servlet
 * add by yaojinshan 2016-10-15 21:47
 * @author Administrator
 *
 */
public class VerifyCodeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Font mFont = new Font("Times New Roman", 0, 20);

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)	throws ServletException, IOException {
		response.setContentType("image/jpeg");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0L);
		HttpSession session = request.getSession();
		int width = 56;
		int height = 24;
		BufferedImage image = new BufferedImage(width, height, 1);
		Graphics g = image.getGraphics();
		Random random = new Random();
		g.fillRect(0, 0, width, height);
		g.setFont(mFont);
		g.setColor(new Color(169, 210, 255));
		for (int i = 0; i < 155; i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int xl = random.nextInt(12);
			int yl = random.nextInt(12);
			g.drawLine(x, y, x + xl, y + yl);
		}
		String sRand = "";
		PropertiesUtil systemProperties = new PropertiesUtil("/systemConfig.properties");
		String system_validateCodeLength = systemProperties.getProperty("system_validateCodeLength");
		for (int i = 0; i < Integer.parseInt(system_validateCodeLength); i++) {
			String rand = String.valueOf(random.nextInt(10));
			sRand = sRand + rand;
			g.setColor(new Color(86, 131, 255));
			g.drawString(rand, 13 * i + 6, 22 - i * 2);
		}
		session.setAttribute("session_validateCode", sRand);
		ServletOutputStream out = response.getOutputStream();
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
		encoder.encode(image);
		out.close();
	}
}